package org.jeecg.modules.carinfo.controller;

import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.carinfo.entity.CarRecord;
import org.jeecg.modules.carinfo.entity.CarRegister;
import org.jeecg.modules.carinfo.service.ICarRegisterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.carinfo.util.OCR;
import org.jeecg.modules.carinfo.util.QueryEnv;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import net.coobird.thumbnailator.Thumbnails;

/**
 * @Description: 车辆登记
 * @Author: jeecg-boot
 * @Date: 2023-11-28
 * @Version: V1.0
 */
@Api(tags = "车辆登记")
@RestController
@RequestMapping("/carinfo/carRegister")
@Slf4j
public class CarRegisterController extends JeecgController<CarRegister, ICarRegisterService> {
    @Autowired
    private ICarRegisterService carRegisterService;
    @Autowired
    private RedisUtil redisUtil;

    public static final String REGISTER = "滨海新区九三集团天津大豆科技有限公司 二号岗";
    public static final String SURVEYOR = "滨海新区九三集团天津大豆科技有限公司 付油验罐区";
    public static final String LEAD_SEALING = "滨海新区九三集团天津大豆科技有限公司 付油区";

    /**
     * 分页列表查询
     *
     * @param carRegister
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车辆登记-分页列表查询")
    @ApiOperation(value = "车辆登记-分页列表查询", notes = "车辆登记-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(CarRegister carRegister,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        carRegister.setPlateNo("*" + carRegister.getPlateNo() + "*");
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param carRegister
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车辆登记-分页列表查询")
    @ApiOperation(value = "车辆登记-分页列表查询--对外", notes = "车辆登记-分页列表查询")
    @GetMapping(value = "/m/list")
    public Result<?> queryPageListM(CarRegister carRegister,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {
        carRegister.setPlateNo("*" + carRegister.getPlateNo() + "*");
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        queryWrapper.orderByDesc("create_time");
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param carRegister
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "车辆登记-分页列表查询")
    @ApiOperation(value = "车辆登记-分页列表查询", notes = "车辆登记-分页列表查询")
    @GetMapping(value = "/examineList")
    public Result<?> examineList(CarRegister carRegister,
                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                 HttpServletRequest req) {
        carRegister.setStatus(0);
        QueryWrapper<CarRegister> queryWrapper = QueryGenerator.initQueryWrapper(carRegister, req.getParameterMap());
        Page<CarRegister> page = new Page<CarRegister>(pageNo, pageSize);
        IPage<CarRegister> pageList = carRegisterService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-添加")
    @ApiOperation(value = "车辆登记-添加", notes = "车辆登记-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody CarRegister carRegister) {
        carRegisterService.save(carRegister);
        return Result.OK("添加成功！");
    }

    /**
     * 查询是否登记
     *
     * @param
     * @return
     */
    @AutoLog(value = "车辆登记-查询是否登记")
    @ApiOperation(value = "车辆登记-查询是否登记", notes = "车辆登记-查询是否登记")
    @GetMapping(value = "/m/exist")
    public Result<?> exist(@RequestParam(name = "plateNo", required = true) String plateNo) {
        LambdaQueryWrapper<CarRegister> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CarRegister::getPlateNo, plateNo);
        if (carRegisterService.list(lambdaQueryWrapper).isEmpty()) {
            return Result.OK("添加成功！");
        }
        return Result.error("添加失败！");
    }

    @Autowired
    QueryEnv queryEnv;

    /**
     * 添加
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-添加")
    @ApiOperation(value = "车辆登记-添加", notes = "车辆登记-添加")
    @PostMapping(value = "/m/add")
    public Result<?> mAdd(@RequestBody CarRegister carRegister) {
        boolean flag = getEnv(carRegister);
        if (flag) {
            carRegister.setStatus(1);
        }
        carRegisterService.save(carRegister);
        return Result.OK("添加成功！");
    }

    private boolean getEnv(CarRegister carRegister) {
        int local = queryEnv.getLocal(carRegister.getPlateNo());
        if (local == 1) {
            return true;
        } else if (local == -1) {
            return false;
        }
        int zhongjiao = queryEnv.getZhongJiao(carRegister.getPlateNo(), carRegister.getPlateColor(), carRegister.getLocatin());
        if (zhongjiao == 1) {
            return true;
        } else if (zhongjiao == -1) {
            return false;
        }
        boolean angmei = queryEnv.getAngMei(carRegister.getVin(), carRegister.getPlateNo(), carRegister.getPlateColor(), carRegister.getLocatin());
        if (angmei) {
            return true;
        }

        return false;
    }

    @AutoLog(value = "检查手机号是否存在")
    @ApiOperation(value = "车辆登记-检查手机号是否存在", notes = "车辆登记-检查手机号是否存在")
    @GetMapping(value = "/m/existPhone")
    public Result<?> existPhone(@RequestParam(name = "phoneNum", required = true) String phoneNum) {
        LambdaQueryWrapper<CarRegister> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CarRegister::getPhoneNum, phoneNum);
        if (carRegisterService.list(lambdaQueryWrapper).isEmpty()) {
            return Result.OK("验证成功！");
        }
        return Result.error("验证失败！");
    }

    /**
     * 编辑
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-编辑")
    @ApiOperation(value = "车辆登记-编辑", notes = "车辆登记-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody CarRegister carRegister) {
        carRegisterService.updateById(carRegister);
        return Result.OK("编辑成功!");
    }

    /**
     * 编辑登记状态
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-编辑登记状态")
    @ApiOperation(value = "车辆登记-编辑登记状态--对外", notes = "车辆登记-编辑登记状态")
    @PostMapping(value = "/m/editStatusLedger")
    public Result<?> editStatusLedger(@RequestBody CarRegister carRegister) {
        LambdaUpdateWrapper<CarRegister> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(CarRegister::getStatusLedger, carRegister.getStatusLedger());
        lambdaUpdateWrapper.eq(CarRegister::getId, carRegister.getId());
        carRegisterService.update(lambdaUpdateWrapper);
        return Result.OK("编辑成功!");
    }

    /**
     * 更新状态
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-更新状态")
    @ApiOperation(value = "车辆登记-更新状态", notes = "车辆登记-更新状态")
    @PutMapping(value = "/editStatus")
    public Result<?> editStatus(@RequestBody CarRegister carRegister) {
        LambdaUpdateWrapper<CarRegister> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(CarRegister::getStatus, 1);
        lambdaUpdateWrapper.eq(CarRegister::getId, carRegister.getId());
        carRegisterService.update(lambdaUpdateWrapper);
        return Result.OK("编辑成功!");
    }

    /**
     * 更新状态
     *
     * @param carRegister
     * @return
     */
    @AutoLog(value = "车辆登记-更新状态")
    @ApiOperation(value = "车辆登记-更新状态--对外", notes = "车辆登记-更新状态--对外--只传id就可以")
    @PutMapping(value = "/m/editStatus")
    public Result<?> editStatusM(@RequestBody CarRegister carRegister) {
        LambdaUpdateWrapper<CarRegister> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(CarRegister::getStatus, 1);
        lambdaUpdateWrapper.eq(CarRegister::getId, carRegister.getId());
        carRegisterService.update(lambdaUpdateWrapper);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车辆登记-通过id删除")
    @ApiOperation(value = "车辆登记-通过id删除", notes = "车辆登记-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        carRegisterService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "车辆登记-批量删除")
    @ApiOperation(value = "车辆登记-批量删除", notes = "车辆登记-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.carRegisterService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车辆登记-通过id查询")
    @ApiOperation(value = "车辆登记-通过id查询", notes = "车辆登记-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        CarRegister carRegister = carRegisterService.getById(id);
        if (carRegister == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(carRegister);
    }

    /**
     * 通过id查询
     *
     * @param
     * @return
     */
    @AutoLog(value = "车辆登记-分类统计")
    @ApiOperation(value = "车辆登记-分类统计", notes = "车辆登记-分类统计")
    @GetMapping(value = "/queryByCount")
    public Result<?> queryByCount() {
        QueryWrapper<CarRegister> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("max(create_time) as create_time");
        Date max = carRegisterService.getOne(queryWrapper).getCreateTime();
        QueryWrapper<CarRegister> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.select("min(create_time) as create_time");
        Date min = carRegisterService.getOne(queryWrapper1).getCreateTime();
        long l = (max.getTime() - min.getTime()) / (3600 * 24 * 1000) + 1;
        QueryWrapper<CarRegister> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.select("count(1) as count");
        Map<String, Object> map = carRegisterService.getMap(queryWrapper2);
        long total = Long.parseLong(map.get("count").toString());
        long average = total / l;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", carRegisterService.getCount());
        jsonObject.put("total", total);
        jsonObject.put("average", average);
        return Result.OK(jsonObject);
    }

    @Autowired
    OCR ocr;

    /**
     * 文件上传统一方法
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/upload")
    public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
        Result<?> result = new Result<>();
        String savePath = "";
        String bizPath = DateUtil.formatDate(new Date());
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        String plateNo = request.getParameter("plateNo");
        String vin = request.getParameter("vin");
        String name = request.getParameter("name");
        String type = request.getParameter("type");
        Long start = System.currentTimeMillis();
        if (name.equals("1")) {
            try {
                JSONObject jsonObject = ocr.getVin(saveFileWithoutWaterMark(file));
                Long end = System.currentTimeMillis();
                System.err.println(vin + (end - start));
                if (jsonObject.getString("plate").equals(plateNo) && jsonObject.getString("vin").equals(vin)) {
                } else {
                    return Result.error("错误");
                }
            } catch (Exception e) {
                Long end = System.currentTimeMillis();
                System.err.println(vin + (end - start));
                return Result.error("错误");
            }
        }
        if (!StringUtils.isEmpty(type)){
            switch (type){
                case "1":
                    savePath = this.uploadLocal(file, bizPath, REGISTER);
                    break;
                case "2":
                    savePath = this.uploadLocal(file, bizPath, SURVEYOR);
                    break;
                case "3":
                    savePath = this.uploadLocal(file, bizPath, LEAD_SEALING);
                    break;
                default:
                    savePath = this.uploadLocal(file, bizPath);
            }
        } else {
            savePath = this.uploadLocal(file, bizPath);
        }

        if (oConvertUtils.isNotEmpty(savePath)) {
            result.setMessage(savePath);
            result.setSuccess(true);
        } else {
            result.setMessage("上传失败！");
            result.setSuccess(false);
        }
        return result;
    }


    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    /**
     * 本地文件上传
     *
     * @param mf      文件
     * @param bizPath 自定义路径
     * @return
     */
    private String uploadLocal(MultipartFile mf, String bizPath, String message) {
        try {
            mf = saveFileWithoutWaterMark(mf);
            BufferedImage image = ImageIO.read(mf.getInputStream());
            Graphics2D g2d = image.createGraphics();
            AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f); // 透明度
            g2d.setComposite(alphaChannel);
            g2d.setColor(Color.RED); // 水印颜色
            int width = image.getWidth();
            int fontWidth = width/25;
            g2d.setFont(new Font("Serif", Font.BOLD, fontWidth)); // 字体样式
            FontMetrics fm = g2d.getFontMetrics();
            LocalDateTime now = LocalDateTime.now(); // 获取当前时间
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm"); // 设置格式
            String formattedNow = now.format(formatter); // 格式化当前时间为字符串
            g2d.drawString(formattedNow, 10, 10 + fm.getAscent());
            g2d.drawString(message, 10, fontWidth + 10 + fm.getAscent());
            g2d.dispose();
            String ctxPath = uploadpath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String orgName = mf.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);
            if (orgName.indexOf(".") != -1) {
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            } else {
                fileName = orgName + "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
          /*  File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);*/
            File savefile = new File(savePath);
            ImageIO.write(image, "png", savefile);
            String dbpath = null;
            if (oConvertUtils.isNotEmpty(bizPath)) {
                dbpath = bizPath + File.separator + fileName;
            } else {
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

    public MultipartFile saveFileWithoutWaterMark(MultipartFile file) {
        try {
            if ((1024 * 1024 * 0.1) <= file.getSize()) {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                //小于 1M 的
                if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {
                    Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.9f).toOutputStream(outputStream);
                }
                // 1 - 2M 的
                else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {
                    Thumbnails.of(file.getInputStream()).scale(0.8f).outputQuality(0.6f).toOutputStream(outputStream);
                }// 2M 以上的
                else if ((1024 * 1024 * 2) < file.getSize()) {
                    Thumbnails.of(file.getInputStream()).scale(0.5f).outputQuality(0.3f).toOutputStream(outputStream);
                }

                byte[] bytes = outputStream.toByteArray();
                InputStream inputStream = new ByteArrayInputStream(bytes);
                //Boolean b=ImageIO.write(ImageIO.read(inputStream),"jpg",new File("D:/111.jpg"));
                // 转换城新的 MultipartFile 对象
                MultipartFile mfileInfos = new MockMultipartFile(file.getOriginalFilename(), file.getOriginalFilename(), file.getContentType(), inputStream);
                System.out.println("源文件大小:" + file.getSize() + "压缩后的大小:" + mfileInfos.getSize());
                return mfileInfos;
            }
            return file;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 导出excel
     *
     * @param request
     * @param carRegister
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CarRegister carRegister) {
        return super.exportXls(request, carRegister, CarRegister.class, "车辆登记");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CarRegister.class);
    }

    /**
     * 本地文件上传
     *
     * @param mf      文件
     * @param bizPath 自定义路径
     * @return
     */
    private String uploadLocal(MultipartFile mf, String bizPath) {
        try {
            mf = saveFileWithoutWaterMark(mf);
            BufferedImage image = ImageIO.read(mf.getInputStream());
            String ctxPath = uploadpath;
            String fileName = null;
            File file = new File(ctxPath + File.separator + bizPath + File.separator);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            String orgName = mf.getOriginalFilename();// 获取文件名
            orgName = CommonUtils.getFileName(orgName);
            if (orgName.indexOf(".") != -1) {
                fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            } else {
                fileName = orgName + "_" + System.currentTimeMillis();
            }
            String savePath = file.getPath() + File.separator + fileName;
          /*  File savefile = new File(savePath);
            FileCopyUtils.copy(mf.getBytes(), savefile);*/
            File savefile = new File(savePath);
            ImageIO.write(image, "png", savefile);
            String dbpath = null;
            if (oConvertUtils.isNotEmpty(bizPath)) {
                dbpath = bizPath + File.separator + fileName;
            } else {
                dbpath = fileName;
            }
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            return dbpath;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "";
    }

    @GetMapping("/m/all")
    public Result<?> mAll(@RequestParam(name = "start") String start,
                          @RequestParam(name = "end") String end) {
        LambdaQueryWrapper<CarRegister> wrapper = Wrappers.lambdaQuery();
        wrapper.between(CarRegister::getCreateTime, start, end);
        List<CarRegister> list = carRegisterService.list(wrapper);
        return Result.OK(list);
    }

}
